<template>
  <div class="rich-text-editor" :class="{ 'fullscreen': isFullScreen }">
    <!-- 工具栏（按功能开关动态渲染） -->
    <div class="editor-toolbar">
      <!-- 新增：字体控制（开关控制） -->
      <template v-if="enableFontControl">
        <div class="toolbar-group">
          <select 
            class="toolbar-select" 
            @change="handleFontFamily($event)"
            title="字体"
          >
            <option value="">字体</option>
            <option value="SimSun">宋体</option>
            <option value="Microsoft YaHei">微软雅黑</option>
            <option value="SimHei">黑体</option>
            <option value="Arial">Arial</option>
            <option value="Georgia">Georgia</option>
          </select>
        </div>
        <div class="toolbar-group">
          <select 
            class="toolbar-select" 
            @change="handleFontSize($event)"
            title="字号"
          >
            <option value="">字号</option>
            <option value="1">12px</option>
            <option value="2">14px</option>
            <option value="3">16px</option>
            <option value="4">18px</option>
            <option value="5">24px</option>
            <option value="6">32px</option>
            <option value="7">48px</option>
          </select>
        </div>
        <div class="toolbar-group">
          <button 
            class="toolbar-btn" 
            title="文字颜色" 
            @click="showTextColorPicker = !showTextColorPicker"
          >
            <i class="fa fa-font" :style="{ color: textColor }"></i>
          </button>
          <input 
            type="color" 
            v-model="textColor" 
            class="color-picker"
            @input="execCommand('foreColor', textColor)"
            v-if="showTextColorPicker"
          >
          <button 
            class="toolbar-btn" 
            title="背景色" 
            @click="showBgColorPicker = !showBgColorPicker"
          >
            <i class="fa fa-highlighter" :style="{ backgroundColor: bgColor }"></i>
          </button>
          <input 
            type="color" 
            v-model="bgColor" 
            class="color-picker"
            @input="execCommand('hiliteColor', bgColor)"
            v-if="showBgColorPicker"
          >
        </div>
        <div class="toolbar-separator"></div>
      </template>

      <!-- 原有：文本格式 -->
      <div class="toolbar-group">
        <button 
          class="toolbar-btn" 
          title="加粗" 
          @click="execCommand('bold')"
          :class="{ active: isCommandActive('bold') }"
        >
          <i class="fa fa-bold"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="斜体" 
          @click="execCommand('italic')"
          :class="{ active: isCommandActive('italic') }"
        >
          <i class="fa fa-italic"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="下划线" 
          @click="execCommand('underline')"
          :class="{ active: isCommandActive('underline') }"
        >
          <i class="fa fa-underline"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="删除线" 
          @click="execCommand('strikeThrough')"
          :class="{ active: isCommandActive('strikeThrough') }"
        >
          <i class="fa fa-strikethrough"></i>
        </button>
      </div>

      <div class="toolbar-separator"></div>

      <!-- 原有：段落格式 -->
      <div class="toolbar-group">
        <select 
          class="toolbar-select" 
          @change="handleFormatBlock($event)"
          title="段落格式"
        >
          <option value="">段落格式</option>
          <option value="p">段落</option>
          <option value="h1">标题 1</option>
          <option value="h2">标题 2</option>
          <option value="h3">标题 3</option>
          <option value="h4">标题 4</option>
          <option value="pre" v-if="enableCodeBlock">代码块</option>
        </select>
      </div>

      <div class="toolbar-separator"></div>

      <!-- 原有：对齐方式 -->
      <div class="toolbar-group">
        <button 
          class="toolbar-btn" 
          title="左对齐" 
          @click="execCommand('justifyLeft')"
          :class="{ active: isCommandActive('justifyLeft') }"
        >
          <i class="fa fa-align-left"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="居中对齐" 
          @click="execCommand('justifyCenter')"
          :class="{ active: isCommandActive('justifyCenter') }"
        >
          <i class="fa fa-align-center"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="右对齐" 
          @click="execCommand('justifyRight')"
          :class="{ active: isCommandActive('justifyRight') }"
        >
          <i class="fa fa-align-right"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="两端对齐" 
          @click="execCommand('justifyFull')"
          :class="{ active: isCommandActive('justifyFull') }"
        >
          <i class="fa fa-align-justify"></i>
        </button>
      </div>

      <div class="toolbar-separator"></div>

      <!-- 原有：列表 -->
      <div class="toolbar-group">
        <button 
          class="toolbar-btn" 
          title="无序列表" 
          @click="execCommand('insertUnorderedList')"
          :class="{ active: isCommandActive('insertUnorderedList') }"
        >
          <i class="fa fa-list-ul"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="有序列表" 
          @click="execCommand('insertOrderedList')"
          :class="{ active: isCommandActive('insertOrderedList') }"
        >
          <i class="fa fa-list-ol"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="减少缩进" 
          @click="execCommand('outdent')"
        >
          <i class="fa fa-outdent"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="增加缩进" 
          @click="execCommand('indent')"
        >
          <i class="fa fa-indent"></i>
        </button>
      </div>

      <div class="toolbar-separator"></div>

      <!-- 新增：表格插入（开关控制） -->
      <template v-if="enableTable">
        <div class="toolbar-group">
          <button 
            class="toolbar-btn" 
            title="插入表格" 
            @click="showTableModal = true"
          >
            <i class="fa fa-table"></i>
          </button>
        </div>
        <div class="toolbar-separator"></div>
      </template>

      <!-- 新增：代码块（开关控制） -->
      <template v-if="enableCodeBlock">
        <div class="toolbar-group">
          <button 
            class="toolbar-btn" 
            title="插入代码块" 
            @click="showCodeBlockModal = true"
          >
            <i class="fa fa-code"></i>
          </button>
        </div>
        <div class="toolbar-separator"></div>
      </template>

      <!-- 新增：查找替换（开关控制） -->
      <template v-if="enableFindReplace">
        <div class="toolbar-group">
          <button 
            class="toolbar-btn" 
            title="查找替换" 
            @click="showFindReplaceModal = true"
          >
            <i class="fa fa-search"></i>
          </button>
        </div>
        <div class="toolbar-separator"></div>
      </template>

      <!-- 原有：链接和图片 -->
      <div class="toolbar-group">
        <button 
          class="toolbar-btn" 
          title="插入链接" 
          @click="handleInsertLink"
        >
          <i class="fa fa-link"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="插入图片" 
          @click="handleInsertImage"
        >
          <i class="fa fa-image"></i>
        </button>
      </div>

      <div class="toolbar-separator"></div>

      <!-- 原有：其他操作 + 新增全屏（开关控制） -->
      <div class="toolbar-group">
        <button 
          class="toolbar-btn" 
          title="清除格式" 
          @click="execCommand('removeFormat')"
        >
          <i class="fa fa-eraser"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="撤销" 
          @click="execCommand('undo')"
        >
          <i class="fa fa-undo"></i>
        </button>
        <button 
          class="toolbar-btn" 
          title="重做" 
          @click="execCommand('redo')"
        >
          <i class="fa fa-repeat"></i>
        </button>
        <button 
          v-if="enableFullScreen"
          class="toolbar-btn" 
          title="全屏/退出全屏" 
          @click="toggleFullScreen"
        >
          <i :class="isFullScreen ? 'fa fa-compress' : 'fa fa-expand'"></i>
        </button>
      </div>

      <!-- 新增：字数统计（开关控制） -->
      <template v-if="enableWordCount">
        <div class="toolbar-separator"></div>
        <div class="toolbar-group word-count-group">
          <span class="word-count">{{ wordCount }} 字</span>
        </div>
      </template>
    </div>

    <!-- 编辑区域 -->
    <div 
      ref="editorRef"
      class="editor-content"
      contenteditable="true"
      @input="handleInput"
      @focus="isFocused = true"
      @blur="isFocused = false"
      v-html="initialContent"
      :data-placeholder="placeholder"
    ></div>

    <!-- 新增：表格插入弹窗 -->
    <div v-if="showTableModal" class="modal-overlay">
      <div class="modal">
        <h3 class="modal-title">插入表格</h3>
        <div class="modal-body">
          <div class="form-group">
            <label>行数:</label>
            <input 
              type="number" 
              v-model.number="tableRows" 
              class="form-control"
              min="1" 
              max="20" 
              value="3"
            >
          </div>
          <div class="form-group">
            <label>列数:</label>
            <input 
              type="number" 
              v-model.number="tableCols" 
              class="form-control"
              min="1" 
              max="10" 
              value="3"
            >
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showTableModal = false" class="btn cancel-btn">取消</button>
          <button @click="confirmInsertTable" class="btn confirm-btn">插入</button>
        </div>
      </div>
    </div>

    <!-- 新增：代码块弹窗 -->
    <div v-if="showCodeBlockModal" class="modal-overlay">
      <div class="modal">
        <h3 class="modal-title">插入代码块</h3>
        <div class="modal-body">
          <div class="form-group">
            <label>编程语言:</label>
            <select v-model="codeLanguage" class="form-control">
              <option value="javascript">JavaScript</option>
              <option value="python">Python</option>
              <option value="html">HTML</option>
              <option value="css">CSS</option>
              <option value="java">Java</option>
              <option value="bash">Bash</option>
            </select>
          </div>
          <div class="form-group">
            <label>代码内容:</label>
            <textarea 
              v-model="codeContent" 
              class="form-control code-input"
              rows="8"
              placeholder="请输入代码..."
            ></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showCodeBlockModal = false" class="btn cancel-btn">取消</button>
          <button @click="confirmInsertCodeBlock" class="btn confirm-btn">插入</button>
        </div>
      </div>
    </div>

    <!-- 新增：查找替换弹窗 -->
    <div v-if="showFindReplaceModal" class="modal-overlay">
      <div class="modal">
        <h3 class="modal-title">查找替换</h3>
        <div class="modal-body">
          <div class="form-group">
            <label>查找:</label>
            <input 
              type="text" 
              v-model="findText" 
              class="form-control"
              @input="highlightMatches"
              placeholder="输入查找内容"
            >
          </div>
          <div class="form-group">
            <label>替换为:</label>
            <input 
              type="text" 
              v-model="replaceText" 
              class="form-control"
              placeholder="输入替换内容"
            >
          </div>
          <div class="form-group checkbox-group">
            <label>
              <input type="checkbox" v-model="matchCase"> 区分大小写
            </label>
          </div>
          <div class="find-stats">
            找到 {{ matchCount }} 个匹配项
          </div>
        </div>
        <div class="modal-footer">
          <button @click="findNext" class="btn">下一个</button>
          <button @click="replaceCurrent" class="btn">替换</button>
          <button @click="replaceAll" class="btn confirm-btn">全部替换</button>
          <button @click="closeFindReplace" class="btn cancel-btn">关闭</button>
        </div>
      </div>
    </div>

    <!-- 原有：链接和图片弹窗 -->
    <div v-if="showLinkModal" class="modal-overlay">
      <div class="modal">
        <h3 class="modal-title">插入链接</h3>
        <div class="modal-body">
          <div class="form-group">
            <label>文本:</label>
            <input 
              type="text" 
              v-model="linkText" 
              class="form-control"
              placeholder="链接显示文本"
            >
          </div>
          <div class="form-group">
            <label>URL:</label>
            <input 
              type="url" 
              v-model="linkUrl" 
              class="form-control"
              placeholder="https://example.com"
              required
            >
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showLinkModal = false" class="btn cancel-btn">取消</button>
          <button @click="confirmInsertLink" class="btn confirm-btn">插入</button>
        </div>
      </div>
    </div>

    <div v-if="showImageModal" class="modal-overlay">
      <div class="modal">
        <h3 class="modal-title">插入图片</h3>
        <div class="modal-body">
          <div class="form-group">
            <label>图片URL:</label>
            <input 
              type="url" 
              v-model="imageUrl" 
              class="form-control"
              placeholder="https://example.com/image.jpg"
              required
            >
          </div>
          <div class="form-group">
            <label>替代文本:</label>
            <input 
              type="text" 
              v-model="imageAlt" 
              class="form-control"
              placeholder="图片描述"
            >
          </div>
          <div class="form-group">
            <label>上传图片:</label>
            <input 
              type="file" 
              accept="image/*" 
              @change="handleImageUpload"
              class="file-input"
            >
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showImageModal = false" class="btn cancel-btn">取消</button>
          <button @click="confirmInsertImage" class="btn confirm-btn">插入</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import hljs from 'highlight.js'; // 代码高亮依赖
import 'highlight.js/styles/github.css'; // 代码高亮样式

// 1. 定义Props（新增功能开关）
const props = defineProps({
  // 原有基础配置
  initialContent: { type: String, default: '' },
  height: { type: Number, default: 300 },
  readonly: { type: Boolean, default: false },
  placeholder: { type: String, default: '请输入内容...' },

  // 新增：功能开关（默认全部启用）
  enableFontControl: { type: Boolean, default: true }, // 字体/颜色控制
  enableTable: { type: Boolean, default: true }, // 表格插入
  enableCodeBlock: { type: Boolean, default: true }, // 代码块
  enableFindReplace: { type: Boolean, default: true }, // 查找替换
  enableWordCount: { type: Boolean, default: true }, // 字数统计
  enableFullScreen: { type: Boolean, default: true } // 全屏模式
});

// 2. 定义Emits
const emit = defineEmits<{
  (e: 'update:content', value: string): void;
  (e: 'input', value: string): void;
  (e: 'focus'): void;
  (e: 'blur'): void;
  (e: 'fullscreen-change', isFullScreen: boolean): void; // 新增全屏事件
}>();

// 3. 状态管理（原有+新增）
const editorRef = ref<HTMLDivElement | null>(null);
const isFocused = ref(false);
let cleanupListeners: (() => void)[] = []; // 事件清理函数集合

// 原有状态
const showLinkModal = ref(false);
const showImageModal = ref(false);
const linkText = ref('');
const linkUrl = ref('');
const imageUrl = ref('');
const imageAlt = ref('');

// 新增：字体/颜色状态
const showTextColorPicker = ref(false);
const showBgColorPicker = ref(false);
const textColor = ref('#000000');
const bgColor = ref('#ffffff');

// 新增：表格状态
const showTableModal = ref(false);
const tableRows = ref(3);
const tableCols = ref(3);

// 新增：代码块状态
const showCodeBlockModal = ref(false);
const codeLanguage = ref('javascript');
const codeContent = ref('');

// 新增：查找替换状态
const showFindReplaceModal = ref(false);
const findText = ref('');
const replaceText = ref('');
const matchCase = ref(false);
const matchCount = ref(0);
const currentMatchIndex = ref(-1);
const matches: Range[] = [];

// 新增：字数统计/全屏状态
const wordCount = ref(0);
const isFullScreen = ref(false);

// 4. 初始化与清理
onMounted(() => {
  // 原有初始化逻辑
  if (editorRef.value) {
    editorRef.value.contentEditable = props.readonly ? 'false' : 'true';
    editorRef.value.setAttribute('data-placeholder', props.placeholder);
  }

  // 监听选择变化（更新工具栏状态）
  const selectionChangeHandler = () => updateToolbarState();
  document.addEventListener('selectionchange', selectionChangeHandler);
  cleanupListeners.push(() => document.removeEventListener('selectionchange', selectionChangeHandler));

  // 监听全屏状态变化
  if (props.enableFullScreen) {
    const fullScreenHandler = () => {
      isFullScreen.value = !!document.fullscreenElement;
      emit('fullscreen-change', isFullScreen.value);
    };
    document.addEventListener('fullscreenchange', fullScreenHandler);
    cleanupListeners.push(() => document.removeEventListener('fullscreenchange', fullScreenHandler));
  }

  // 初始化字数统计
  if (props.enableWordCount) {
    calculateWordCount();
  }

  // 点击外部关闭颜色选择器
  const clickOutsideHandler = (e: MouseEvent) => {
    const target = e.target as HTMLElement;
    if (!target.closest('.toolbar-btn') && target.tagName !== 'INPUT') {
      showTextColorPicker.value = false;
      showBgColorPicker.value = false;
    }
  };
  document.addEventListener('click', clickOutsideHandler);
  cleanupListeners.push(() => document.removeEventListener('click', clickOutsideHandler));
});

// 清理事件监听
onUnmounted(() => {
  cleanupListeners.forEach(cleanup => cleanup());
  // 退出全屏
  if (isFullScreen.value) {
    document.exitFullscreen().catch(() => {});
  }
  // 清除查找高亮
  clearHighlights();
});

// 5. 核心方法（原有+新增）
/**
 * 执行富文本命令
 */
const execCommand = (command: string, value?: string) => {
  if (!editorRef.value || props.readonly) return;
  editorRef.value.focus();
  // 处理特殊命令（如格式块需加<>）
  const cmdValue = command === 'formatBlock' && value ? `<${value}>` : value;
  document.execCommand(command, false, cmdValue || null);
  handleInput();
  updateToolbarState();
};

/**
 * 检查命令是否激活（更新按钮高亮）
 */
const isCommandActive = (command: string): boolean => {
  if (!editorRef.value || !isFocused.value) return false;
  return document.queryCommandState(command);
};

/**
 * 更新工具栏状态（触发重渲染）
 */
const updateToolbarState = () => {
  if (isFocused.value) {
    // 触发Vue响应式更新（无需具体逻辑，仅触发重渲染）
    textColor.value = textColor.value;
  }
};

/**
 * 处理输入事件（更新内容+字数统计）
 */
const handleInput = () => {
  if (!editorRef.value) return;
  const content = editorRef.value.innerHTML;
  emit('input', content);
  emit('update:content', content);
  // 更新字数统计
  if (props.enableWordCount) {
    calculateWordCount();
  }
};

// 6. 新增功能实现
/**
 * 字体选择
 */
const handleFontFamily = (e: Event) => {
  const value = (e.target as HTMLSelectElement).value;
  if (value) execCommand('fontName', value);
  (e.target as HTMLSelectElement).value = '';
};

/**
 * 字号选择
 */
const handleFontSize = (e: Event) => {
  const value = (e.target as HTMLSelectElement).value;
  if (value) execCommand('fontSize', value);
  (e.target as HTMLSelectElement).value = '';
};

/**
 * 段落格式（原有逻辑保留）
 */
const handleFormatBlock = (e: Event) => {
  const value = (e.target as HTMLSelectElement).value;
  if (value) execCommand('formatBlock', value);
  (e.target as HTMLSelectElement).value = '';
};

/**
 * 插入表格
 */
const confirmInsertTable = () => {
  if (!editorRef.value || tableRows.value < 1 || tableCols.value < 1) return;
  // 构建表格HTML（带基础样式）
  let tableHtml = `
    <table style="border-collapse: collapse; width: 100%; margin: 8px 0;">
      <tbody>
  `;
  for (let i = 0; i < tableRows.value; i++) {
    tableHtml += '<tr>';
    for (let j = 0; j < tableCols.value; j++) {
      tableHtml += `<td style="border: 1px solid #ccc; padding: 8px;">单元格 ${i+1}-${j+1}</td>`;
    }
    tableHtml += '</tr>';
  }
  tableHtml += '</tbody></table>';
  execCommand('insertHTML', tableHtml);
  showTableModal.value = false;
};

/**
 * 插入代码块（依赖highlight.js）
 */
const confirmInsertCodeBlock = () => {
  if (!editorRef.value || !codeContent.value.trim()) return;
  // 代码高亮处理
  const highlightedCode = hljs.highlight(codeContent.value, {
    language: codeLanguage.value
  }).value;
  // 构建代码块HTML（带复制功能）
  const codeBlockHtml = `
    <pre style="position: relative; background: #f5f5f5; padding: 16px; border-radius: 4px; overflow-x: auto; margin: 8px 0;">
      <code class="language-${codeLanguage.value}">${highlightedCode}</code>
      <button 
        class="copy-code-btn" 
        onclick="navigator.clipboard.writeText(\`${codeContent.value.replace(/`/g, '\\`').replace(/\\(?![`\\])/g, '\\\\')}\`)"
        style="position: absolute; top: 8px; right: 8px; padding: 4px 8px; font-size: 12px; background: rgba(255,255,255,0.8); border: 1px solid #ddd; border-radius: 4px; cursor: pointer;"
      >
        <i class="fa fa-copy"></i> 复制
      </button>
    </pre>
  `;
  execCommand('insertHTML', codeBlockHtml);
  showCodeBlockModal.value = false;
  codeContent.value = '';
};

/**
 * 查找替换 - 高亮匹配项
 */
const highlightMatches = () => {
  clearHighlights();
  matches.length = 0;
  if (!editorRef.value || !findText.value.trim()) {
    matchCount.value = 0;
    return;
  }

  // 正则匹配（区分大小写）
  const regex = new RegExp(findText.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), matchCase.value ? 'g' : 'gi');
  const text = editorRef.value.innerText;
  let match: RegExpExecArray | null;
  let offset = 0;

  // 遍历匹配项并标记
  while ((match = regex.exec(text)) !== null) {
    const range = getTextRange(editorRef.value, offset + match.index, offset + regex.lastIndex);
    if (range) {
      matches.push(range);
      // 添加高亮样式
      const span = document.createElement('span');
      span.className = 'search-highlight';
      range.surroundContents(span);
      offset = regex.lastIndex;
    }
  }
  matchCount.value = matches.length;
  currentMatchIndex.value = -1;
};

/**
 * 查找替换 - 获取文本范围（辅助函数）
 */
const getTextRange = (parent: Node, start: number, end: number): Range | null => {
  const range = document.createRange();
  let currentNode: Node | null = parent;
  let currentOffset = 0;

  // 递归遍历文本节点
  const traverse = (node: Node): boolean => {
    if (node.nodeType === Node.TEXT_NODE) {
      const textLength = (node.textContent || '').length;
      if (currentOffset + textLength >= start) {
        const startOffset = Math.max(0, start - currentOffset);
        const endOffset = Math.min(textLength, end - currentOffset);
        range.setStart(node, startOffset);
        range.setEnd(node, endOffset);
        return true;
      }
      currentOffset += textLength;
    } else if (node.nodeType === Node.ELEMENT_NODE && !['SCRIPT', 'STYLE'].includes(node.nodeName)) {
      for (let i = 0; i < node.childNodes.length; i++) {
        if (traverse(node.childNodes[i])) return true;
      }
    }
    return false;
  };

  return traverse(currentNode) ? range : null;
};

/**
 * 查找替换 - 清除高亮
 */
const clearHighlights = () => {
  if (!editorRef.value) return;
  const highlights = editorRef.value.querySelectorAll('.search-highlight');
  highlights.forEach(span => {
    const parent = span.parentNode;
    while (span.firstChild) parent?.insertBefore(span.firstChild, span);
    parent?.removeChild(span);
  });
};

/**
 * 查找替换 - 下一个匹配项
 */
const findNext = () => {
  if (matches.length === 0) return;
  currentMatchIndex.value = (currentMatchIndex.value + 1) % matches.length;
  const range = matches[currentMatchIndex.value];
  const selection = window.getSelection();
  selection?.removeAllRanges();
  selection?.addRange(range);
  // 滚动到可视区域
  range.startContainer.parentElement?.scrollIntoView({ behavior: 'smooth', block: 'center' });
};

/**
 * 查找替换 - 替换当前匹配项
 */
const replaceCurrent = () => {
  if (currentMatchIndex.value === -1 || currentMatchIndex.value >= matches.length) return;
  const range = matches[currentMatchIndex.value];
  range.deleteContents();
  range.insertNode(document.createTextNode(replaceText.value));
  highlightMatches(); // 重新查找
};

/**
 * 查找替换 - 替换所有
 */
const replaceAll = () => {
  if (matches.length === 0) return;
  clearHighlights();
  const regex = new RegExp(findText.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), matchCase.value ? 'g' : 'gi');
  const walker = document.createTreeWalker(editorRef.value!, NodeFilter.SHOW_TEXT, null, false);
  const textNodes: Text[] = [];
  let node: Node | null;

  // 收集所有文本节点
  while ((node = walker.nextNode()) !== null) {
    textNodes.push(node as Text);
  }

  // 替换文本
  textNodes.forEach(textNode => {
    textNode.textContent = textNode.textContent?.replace(regex, replaceText.value) || '';
  });
  handleInput();
  highlightMatches();
};

/**
 * 查找替换 - 关闭弹窗
 */
const closeFindReplace = () => {
  clearHighlights();
  showFindReplaceModal.value = false;
  findText.value = '';
  replaceText.value = '';
  matchCount.value = 0;
};

/**
 * 字数统计
 */
const calculateWordCount = () => {
  if (!editorRef.value) return;
  // 去除HTML标签，统计纯文本字数
  const pureText = editorRef.value.innerText.replace(/\s+/g, '');
  wordCount.value = pureText.length;
};

/**
 * 全屏切换
 */
const toggleFullScreen = () => {
  if (!editorRef.value) return;
  if (isFullScreen.value) {
    document.exitFullscreen().catch(err => console.error('退出全屏失败:', err));
  } else {
    editorRef.value.parentElement?.requestFullscreen().catch(err => console.error('进入全屏失败:', err));
  }
};

// 7. 原有功能方法（保留）
const handleInsertLink = () => {
  if (!editorRef.value || props.readonly) return;
  const selection = window.getSelection();
  linkText.value = selection?.toString() || '';
  linkUrl.value = '';
  showLinkModal.value = true;
};

const confirmInsertLink = () => {
  if (!linkUrl.value || !editorRef.value) return;
  const text = linkText.value || linkUrl.value;
  execCommand('createLink', linkUrl.value);
  // 设置链接新窗口打开
  const selection = window.getSelection();
  if (selection?.rangeCount) {
    const anchor = selection.getRangeAt(0).commonAncestorContainer.closest('a');
    if (anchor) {
      anchor.target = '_blank';
      anchor.rel = 'noopener noreferrer';
    }
  }
  showLinkModal.value = false;
};

const handleInsertImage = () => {
  if (props.readonly) return;
  imageUrl.value = '';
  imageAlt.value = '';
  showImageModal.value = true;
};

const handleImageUpload = (e: Event) => {
  const input = e.target as HTMLInputElement;
  if (!input.files?.length) return;
  const file = input.files[0];
  const reader = new FileReader();
  reader.onload = (event) => {
    imageUrl.value = event.target?.result as string;
  };
  reader.readAsDataURL(file);
};

const confirmInsertImage = () => {
  if (!imageUrl.value || !editorRef.value) return;
  execCommand('insertImage', imageUrl.value);
  // 设置图片样式和替代文本
  const images = editorRef.value.querySelectorAll('img');
  if (images.length) {
    const lastImg = images[images.length - 1];
    if (imageAlt.value) lastImg.alt = imageAlt.value;
    lastImg.style.maxWidth = '100%';
    lastImg.style.height = 'auto';
    lastImg.style.margin = '8px 0';
  }
  showImageModal.value = false;
};

// 8. 监听readonly变化（原有逻辑保留）
watch(() => props.readonly, (newVal) => {
  if (editorRef.value) {
    editorRef.value.contentEditable = newVal ? 'false' : 'true';
  }
});

// 9. 暴露公共方法
defineExpose({
  // 原有方法
  getContent: (): string => editorRef.value?.innerHTML || '',
  setContent: (content: string) => {
    if (editorRef.value) {
      editorRef.value.innerHTML = content;
      handleInput();
    }
  },
  clearContent: () => {
    if (editorRef.value) {
      editorRef.value.innerHTML = '';
      handleInput();
    }
  },
  // 新增方法
  getWordCount: (): number => wordCount.value, // 获取字数
  toggleFullScreen, // 切换全屏
  focus: () => editorRef.value?.focus(), // 聚焦编辑器
  clearHighlights // 清除查找高亮
});
</script>

<style lang="scss" scoped>
// 原有变量定义
$primary-color: #409eff;
$primary-light: #e6f7ff;
$border-color: #e5e7eb;
$text-color: #303133;
$text-light: #606266;
$bg-color: #fff;
$hover-color: #f5f7fa;
$active-color: #d9ecff;
$separator-color: #e5e7eb;
$modal-bg: rgba(0, 0, 0, 0.5);

.rich-text-editor {
  border: 1px solid $border-color;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;

  // 全屏样式
  &.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    border: none;
    border-radius: 0;
    box-shadow: none;
  }
}

// 工具栏样式（原有+新增）
.editor-toolbar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 8px 12px;
  background-color: #f9f9f9;
  border-bottom: 1px solid $border-color;
  gap: 4px;
  z-index: 1;

  // 全屏时工具栏固定顶部
  .rich-text-editor.fullscreen & {
    position: sticky;
    top: 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.toolbar-group {
  display: flex;
  align-items: center;
  gap: 2px;
}

.toolbar-separator {
  width: 1px;
  height: 24px;
  background-color: $separator-color;
  margin: 0 4px;
}

.toolbar-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  border-radius: 4px;
  color: $text-color;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;

  &:hover {
    background-color: $hover-color;
  }

  &.active {
    background-color: $active-color;
    color: $primary-color;
  }

  &:disabled {
    color: #ccc;
    cursor: not-allowed;
    background-color: transparent;
  }
}

.toolbar-select {
  height: 32px;
  padding: 0 8px;
  border: 1px solid $border-color;
  border-radius: 4px;
  background-color: $bg-color;
  color: $text-color;
  font-size: 14px;
  cursor: pointer;

  &:focus {
    outline: none;
    border-color: $primary-color;
  }
}

// 新增：颜色选择器样式
.color-picker {
  position: absolute;
  width: 28px;
  height: 28px;
  padding: 0;
  border: none;
  cursor: pointer;
  background: transparent;
  z-index: 2;

  &::-webkit-color-swatch-wrapper {
    padding: 0;
  }

  &::-webkit-color-swatch {
    border: none;
    border-radius: 3px;
  }
}

// 新增：字数统计样式
.word-count-group {
  margin-left: auto;
  color: $text-light;
  font-size: 12px;
  padding: 0 8px;
}

// 编辑区域样式（原有+新增）
.editor-content {
  min-height: v-bind(height + 'px');
  padding: 16px;
  background-color: $bg-color;
  color: $text-color;
  outline: none;
  line-height: 1.6;

  // 全屏时高度自适应
  .rich-text-editor.fullscreen & {
    min-height: calc(100vh - 50px);
  }

  &:empty:before {
    content: attr(data-placeholder);
    color: #999;
    pointer-events: none;
  }

  // 原有元素样式保留
  h1, h2, h3, h4 {
    margin: 16px 0 8px;
    font-weight: 600;
  }

  p {
    margin: 8px 0;
  }

  ul, ol {
    margin: 8px 0;
    padding-left: 24px;
  }

  a {
    color: $primary-color;
    text-decoration: underline;
  }

  img {
    max-width: 100%;
    height: auto;
    margin: 8px 0;
  }

  pre {
    background-color: #f5f5f5;
    padding: 16px;
    border-radius: 4px;
    overflow-x: auto;
    font-family: monospace;
    margin: 8px 0;
  }

  // 新增：表格样式
  table {
    border-collapse: collapse;
    width: 100%;
    margin: 8px 0;
  }

  td, th {
    border: 1px solid #ccc;
    padding: 8px;
  }

  // 新增：查找高亮样式
  .search-highlight {
    background-color: #fff3cd;
    padding: 0 2px;
    border-radius: 2px;
  }
}

// 弹窗样式（原有+新增）
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: $modal-bg;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  width: 100%;
  max-width: 400px;
  background-color: $bg-color;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.modal-title {
  margin: 0;
  padding: 16px 20px;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 1px solid $border-color;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  color: $text-color;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid $border-color;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;

  &:focus {
    outline: none;
    border-color: $primary-color;
  }
}

// 新增：代码块输入框样式
.code-input {
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
}

// 新增：查找替换复选框样式
.checkbox-group {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
}

// 新增：查找统计信息样式
.find-stats {
  margin-top: 8px;
  font-size: 12px;
  color: $text-light;
}

.file-input {
  width: 100%;
  padding: 6px 0;
  font-size: 14px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 12px 20px;
  border-top: 1px solid $border-color;
  background-color: #f9f9f9;
}

.btn {
  padding: 6px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: $text-color;

  &:hover {
    background-color: #e9e9e9;
  }
}

.confirm-btn {
  background-color: $primary-color;
  color: white;

  &:hover {
    background-color: #66b1ff;
  }
}

// 响应式调整
@media (max-width: 768px) {
  .editor-toolbar {
    padding: 4px 8px;
  }

  .toolbar-btn {
    width: 28px;
    height: 28px;
    font-size: 12px;
  }

  .toolbar-select {
    height: 28px;
    font-size: 12px;
  }

  .modal {
    width: 90%;
  }

  // 全屏时隐藏部分工具栏项
  .rich-text-editor.fullscreen .toolbar-group:nth-child(1),
  .rich-text-editor.fullscreen .toolbar-group:nth-child(2) {
    display: none;
  }
}
</style>